package com.liugh.fastDFS;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.StorageClient;
import org.csource.fastdfs.StorageClient1;

import static com.liugh.fastDFS.ConnectionPool.getPoolInstance;

public class FastDFSClient {
    private static Log logger = LogFactory.get();

    static {
        try {
            ConnectionPool.getPoolInstance();
        } catch (Exception e) {
            logger.error("FastDFS Client Init Fail!",e);
        }
    }

    public static String[] fileUpload(FastDFSFile fastDFSFile) throws Exception {
        NameValuePair[] metaList = new NameValuePair[1];
        metaList[0] = new NameValuePair("author", fastDFSFile.getAuthor());
        long startTime = System.currentTimeMillis();

        String[] address;
        StorageClient1 client1 = null;
        try {
            client1 = ConnectionPool.getPoolInstance().checkout();
            address = client1.upload_file(fastDFSFile.getContent(), fastDFSFile.getExt(), metaList);
            logger.info("上传文件用时:" + (System.currentTimeMillis() - startTime) + " ms");
            ConnectionPool.getPoolInstance().checkin(client1);
        } catch (InterruptedException e) {
            // 确实没有空闲连接,并不需要删除与fastdfs连接
            throw e;
        } catch (Exception e) {
            // 发生io异常等其它异常，默认删除这次连接重新申请
            ConnectionPool.getPoolInstance().drop(client1);
            e.printStackTrace();
            throw e;
        }
        return address;

    }
    public static void deleteFile(String groupName, String remoteFileName) throws Exception {
        StorageClient storageClient = getPoolInstance().checkout();
        storageClient.delete_file(groupName, remoteFileName);
        logger.info("成功删除文件 :"  + remoteFileName);
    }
}